package tomcat.demo;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * NIO 客户端
 */
public class MyClient {
    public static void main(String[] args) throws Exception{
        serverSocketChannel();
    }

    private static Selector selector;

    public static void serverSocketChannel() throws Exception{
         selector = Selector.open();

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("127.0.0.1",8080));

        socketChannel.register(selector, SelectionKey.OP_CONNECT);

        while (true){
            selector.select();

            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            while(iterator.hasNext()){
                SelectionKey key = iterator.next();

                iterator.remove();

                if(key.isConnectable()){
                    handleConnect(key);
                }else if(key.isReadable()){
                    handleRead(key);
                }
            }
        }
    }

    private static void handleRead(SelectionKey key) throws Exception{
        SocketChannel channel = (SocketChannel) key.channel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024*2);
        channel.read(byteBuffer);

        System.out.println("client received msg from server：" + new String(byteBuffer.array()));

        // 数据写入通道
        String msg = "Hello Server!";
        channel.write(ByteBuffer.wrap(msg.getBytes()));
        channel.close();
    }

    private static void handleConnect(SelectionKey key) throws Exception {
        SocketChannel channel = (SocketChannel) key.channel();
        //连接挂起的话，就结束
        if (channel.isConnectionPending()){
            channel.finishConnect();
        }
        channel.configureBlocking(false);
        //建立连接后，跟客户端发送信息
        String resp = "我是客户端，请你处理";
        channel.write(ByteBuffer.wrap(resp.getBytes()));
        // 通道注册到选择器，并且这个通道只对读事件感兴趣
        channel.register(selector, SelectionKey.OP_READ);

    }
}
